const Base = require("./base.js");

module.exports = class extends Base {
  indexAction() {
    return this.display();
  }

  async loginAction() {
    let result = {};
    let data = this.post();
    const db = this.model("admin");
    //1.根据用户名查询用户
    const admin = await db
      .where({
        name: data.name
      })
      .find();
    if (!admin) {
      result.errno = 1;
    } else if (admin.pass !== data.pass) {
      result.errno = 2;
    } else {
      result.errno = 0;
      delete admin.pass;
      const token = think.uuid();
      await this.cache(token, admin);
      result.data = admin;
      result.token = token;
    }
    return this.json(this.format(result));
  }

  async tokenAction() {
    const sT = Date.now();
    const post = this.post();
    const db = this.model("admin");
    const result = {};
    const token = await this.cache(post.token);
    if (!token || !token.id) result.errno = 3;
    else {
      try {
        result.errno = 0;
        result.data = await db.find(token.id);
      } catch (e) {
        result.errno = -1;
        result.errmsg = e.toString();
      }
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }
};
